<template>
	<view class="miss_password">
		<view class="form">
			<i-formItem title="手机号">
				<input v-model="formData.mobile" type="number" placeholder="请输入手机号">
			</i-formItem>
			<i-verification type="bindWX" v-model="formData.smsCode" :mobile="formData.mobile" color="#FB652E"
				right="108rpx">
			</i-verification>
			<view style="height: 40rpx;"></view>
			<i-buttons radius="4" padding="18rpx 0" color="#fff" size="32" bgColor="#FB652E" @click="confirm">立即绑定
			</i-buttons>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import {
		reactive,
		ref
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		appWxBinding
	} from '../../api/index';
	import {
		showTost,
		navTo,
		checkForm,
		setStorage
	} from '../../utils/common';
	import {
		smsCodeReg,
		phoneReg
	} from '../../utils/regs';
	import useStore from '../../stores/index'
	
	const store = useStore()
	const formData = reactive({
		"mobile": "",
		"smsCode": 0,
		openid: ''
	})

	onLoad((option) => {
		if (option && option.openId) {
			formData.openid = option.openId
		}
	})
	const confirm = async () => {

		const flag = checkForm(formData, ['openid'], {
			mobile: {
				reg: phoneReg,
				message: '请输入正确手机号'
			},
			smsCode: {
				reg: smsCodeReg,
				message: '请输入6位验证码'
			}
		})
		if (flag) {
			return
		}

		const {
			data
		} = await appWxBinding({
			mobile: formData.mobile,
			openid: formData.openid,
			smsCode: Number(formData.smsCode),
		})
		if (data.token && data.userId) {
			showTost('绑定成功！即将自动登录', async () => {
				setStorage('token', data.token)
				setStorage('userId', data.userId)
				await store.setUserInfo();
				navTo('/pages/user/user', 'switchTab')
			})
		}
	}
</script>

<style lang="scss" scoped>
	.miss_password {
		width: 100%;
		height: 100vh;
		overflow: hidden;

		.form {
			width: calc(100% - 64rpx);
			margin: 0 auto;
		}

		input {
			width: 72%;
		}

		.message {
			padding: 20rpx 0;
			@include dfont(24rpx);
			color: #A0A0AD;
		}
	}
</style>
